<?php

namespace APP\Ctrl;
use CMS\Ctrl as Base;
use CMS\Helper as Helper;

class Cron extends Base {
	protected $layout = 'none';

	// construct
	public function run() {
		$this->blizzard(); // optimal: run every 5 minutes

		// vacuum once in a while :P
		$this->db->exec("VACUUM;");
	}

	// handle blizzard api
	private function blizzard() {
        $r_name = rawurlencode($this->settings['blizz_realm']);
        $g_name = rawurlencode($this->settings['blizz_guild']);
	
		// update realm
		$realm = $this->db->querySingle("SELECT time FROM blizzard WHERE api = 'realm'");
		if(!$realm || $realm < time() - 295) {
			$info = @file_get_contents("http://eu.battle.net/api/wow/realm/status?realms={$r_name}");
			if(!is_null(json_decode($info))) {
				$data = $this->db->escapeString(serialize(json_decode($info)));
				if(!$realm) @$this->db->exec("INSERT INTO blizzard (api, value, time) VALUES ('realm', '{$data}', '". time() ."')");
				else @$this->db->exec("UPDATE blizzard SET value='{$data}', time='". time() ."' WHERE api = 'realm'");
			}
		}

		// update guild
		$guild = $this->db->querySingle("SELECT time FROM blizzard WHERE api = 'guild'");
		if(!$guild || $guild < time() - 295) {
			$info = @file_get_contents("http://eu.battle.net/api/wow/guild/{$r_name}/{$g_name}?fields=members");
			if(!is_null(json_decode($info))) {
				$data = $this->db->escapeString(serialize(json_decode($info)));
				if(!$guild) @$this->db->exec("INSERT INTO blizzard (api, value, time) VALUES ('guild', '{$data}', '". time() ."')");
				else @$this->db->exec("UPDATE blizzard SET value='{$data}', time='". time() ."' WHERE api = 'guild'");
			}
		}
	}
}